import React, {
  FC,
  ReactNode,
  useCallback,
  useEffect,
  useRef,
  useState,
} from 'react';
import classNames from 'classnames';
import './style.less';
//获取元素的纵坐标（相对于窗口）
export function getTop(e: HTMLElement | any) {
  if (!e) {
    return 0;
  }
  let offset = e.offsetTop;
  if (e.offsetParent != null) {
    offset += getTop(e.offsetParent);
  }
  return offset;
}

export interface affixTypeProps {
  /**
   * 距离顶部生效距离
   * */
  offsetTop?: number;
  /**
   * 距离底部生效距离
   * */
  offsetBottom?: number;
}

const Affix: FC<affixTypeProps> = props => {
  const refDom = useRef(document.createElement('div'));
  const [fixed, setFixed] = useState(false);
  const [initDomOffset, setInitDomOffset] = useState<{
    x?: number;
    y?: number;
  }>({ x: 0, y: 0 }); // 当前被控dom的初始位置
  // css
  const [styleTans, setStyleTans] = useState({});
  const { children, offsetTop = 0 } = props;
  /**
   * 是否靠近视窗顶部
   * **/
  // const isTop = () =>{
  //   const top = refDom.current.getBoundingClientRect().top;
  //   if (offsetTop >= top){
  //     return true;
  //   }
  //   return false;
  // }

  // 当前被控dom的初始位置
  useEffect(() => {
    setInitDomOffset({
      y: getTop(refDom.current),
    });
  }, []);

  /*
   * 默认绑定window事件
   * */
  const onScrollWindow = useCallback(
    e => {
      /**
       * 靠近视窗顶部
       * **/
      const currentDomTop = initDomOffset.y as number;
      const currentScrollTop = document.getElementsByTagName('html')[0]
        .scrollTop;
      if (currentScrollTop + offsetTop >= currentDomTop) {
        setStyleTans({
          position: 'fixed',
          top: offsetTop,
        });
        setFixed(true);
      } else {
        setStyleTans({});
        setFixed(false);
      }
      /**
       * 靠近视窗底部
       * **/
      console.log(e.target.scrollTop);
    },
    [initDomOffset],
  );

  useEffect(() => {
    window.addEventListener('scroll', onScrollWindow);
    return () => {
      window.removeEventListener('scroll', onScrollWindow);
    };
  }, [onScrollWindow]);

  const classNameTrans = classNames({
    'ant-affix': fixed,
  });

  return (
    <div ref={refDom} className={classNameTrans} style={styleTans}>
      {children}
    </div>
  );
};
export default Affix;
